using System.ServiceModel;
using Framework.Remoting.Client;
using Framework.Tests.Wcf.Client.ServiceDefinition;
using Rhino.Mocks;
using Xunit;

namespace Framework.Tests.Wcf.Client
{
    public class AutoManagedChannelManagerTest : ManagedChannelManagerTestBase<AutoManagedRequest>
    {
        [Fact]
        public void Should_keep_channel_when_BeginRequest()
        {
            MockBeginRequest(CommunicationState.Opened);
            MockRepository.ReplayAll();

            var expected = Target.BeginRequest<IContract>(WcfServiceInfo);
            var actual = Target.BeginRequest<IContract>(WcfServiceInfo);

            Assert.Equal(expected, actual);

            MockRepository.VerifyAll();
        }

        [Fact]
        public void Should_recreate_channel_when_current_channel_is_not_opened()
        {
            MockBeginRequest();
            MockBeginRequest(CommunicationState.Closed);

            MockRepository.ReplayAll();
            var expected = Target.BeginRequest<IContract>(WcfServiceInfo);
            var actual = Target.BeginRequest<IContract>(WcfServiceInfo);

            Assert.Equal(expected, actual);

            MockRepository.VerifyAll();
        }

        [Fact]
        public void When_state_is_not_faulted_or_closed_Then_Keep_Channel_Open()
        {
            ChannelContractMock.Expect(x => x.State).Return(CommunicationState.Opened).Repeat.Any();
            MockRepository.ReplayAll();
            Target.EndRequest(ChannelContractMock);
            MockRepository.VerifyAll();
        }

        [Fact]
        public void Should_close_channel_when_dispose()
        {
            MockBeginRequest();
            ChannelContractMock.Expect(x => x.State).Return(CommunicationState.Opened).Repeat.Any();
            ChannelContractMock.Expect(x => x.Close());
            MockRepository.ReplayAll();
            Target.BeginRequest<IContract>(WcfServiceInfo);
            Target.Dispose();
            MockRepository.VerifyAll();
        }
    }
}